package cn.zsc.netdisk.service;

import cn.zsc.netdisk.service.cache.MobileCodeCacheService;
import cn.zsc.netdisk.util.SendSmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 保存用户手机验证码
 * @author ccying
 * @date 2021/2/21
 */
@Service
@Slf4j
public class MobileCodeService {
    private final MobileCodeCacheService cache;

    public MobileCodeService(MobileCodeCacheService cache) {
        this.cache = cache;
    }

    /**
     * 保存手机号码-手机验证码键值对
     * */
    public void save(String number, int code) {
        log.info("保存手机号码-手机验证码键值对");
        this.cache.save(number, code);
    }

    /**
     * 根据手机号码获取手机验证码
     * @param number 手机号码
     * @return 手机验证码
     * */
    public int get(String number) {
        log.info("根据手机号码获取手机验证码");
        Integer code = this.cache.get(number);
        if (code == null) {
            return -1;
        } else {
            return code;
        }
    }

    /**
     * 发送手机验证码
     * @param mobileNumber 手机号码
     * @return 手机验证码
     * */
    public int send(String mobileNumber) {
        log.info("发送手机验证码");
        int mobileCode = SendSmsUtil.send(mobileNumber);
        if (mobileCode != -1) {
            this.save(mobileNumber, mobileCode);
        }
        return mobileCode;
    }
}
